package com.anuo.app.common.utils;


import com.anuo.app.common.entity.EntityBase;
import com.anuo.app.common.globalhandle.AppException;
import com.anuo.app.modules.coach.entity.Coach;
import com.anuo.app.modules.study.entity.Product;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class CollectionUtil {


    public static boolean isEmpty(Collection collection) {
        return (collection == null || collection.isEmpty());
    }

    public static boolean isNotEmpty(Collection collection){
        return !isEmpty(collection);
    }

    public static<K,V> boolean isEmpty(Map<K,V> map) {
        return (map == null || map.isEmpty());
    }

    public static <K,V> boolean isNotEmpty(Map<K,V> map){
        return !isEmpty(map);
    }

    public static <T> T getFirst(Collection<T> collection) {
        if (!isEmpty(collection)) {
            return collection.iterator().next();
        } else {
            return null;
        }
    }


    /**
     * 将List A 转为 List B
     * 如果有其他需求,请参考 : https://stackoverflow.com/questions/7383624/how-to-transform-listx-to-another-listy/45930123#45930123
     *
     * @param sourseList
     * @param destinationList
     * @param <TSourse>
     * @param <TResult>
     */
    public static <TSourse, TResult> void ConvertList(List<TSourse> sourseList
            , List<TResult> destinationList) {
        if (sourseList.size() > 0) {
            for (TSourse obj : sourseList) {
                TResult tResult = (TResult) obj;
                if (tResult == null) {
                    throw new AppException("出错：在ListEx.ToList方法中,对象转型失败.");
                }
                destinationList.add(tResult);
            }
        }
    }

    public static void main(String[] args) {

        //getFirst 方法使用
        List<Product> productList = new ArrayList<>();
        productList.add(new Product("cpu", 1.23));
        productList.add(new Product("memory", 2.33));
        Product product = CollectionUtil.getFirst(productList);
        if (product != null) {
            String name = product.getName().trim();
            name = StringUtil.strip(name, "pu");
            System.out.println(name);
        }
        //getFirst 方法使用 --结束

        //ConvertList 方法调用
        List<EntityBase> entityBaseList = new ArrayList<>();
        Coach coach = new Coach();
        coach.setId("123");
        entityBaseList.add(coach);

        List<Coach> coachList = new ArrayList<>();
        ConvertList(entityBaseList, coachList);

        System.out.println(JsonUtil.toJson(coachList));
        //ConvertList 方法调用 --结束
    }
}
